﻿using System;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Xml.Highlightings;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using SPCAFContrib.ReSharper.Common;
using SPCAFContrib.ReSharper.Common.Attributes;
using SPCAFContrib.ReSharper.Common.Extensions;
using SPCAFContrib.ReSharper.Common.XmlAnalysis;
using SPCAFContrib.ReSharper.Consts;
using SPCAFContrib.ReSharper.Inspection.Xml.SPCAF;

[assembly: RegisterConfigurableSeverity(SPC015210Highlighting.CheckId,
  null,
  Consts.SPCAF_CORRECTNESS_GROUP,
  SPC015210Highlighting.CheckId + ": " + SPC015210Highlighting.Message,
  "If ContentType defines attribute 'FeatureId' the value must be correct and include braces.",
  Severity.WARNING,
  false, Internal = false)]

namespace SPCAFContrib.ReSharper.Inspection.Xml.SPCAF
{
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution)]
    public class DefineCorrectParentFeatureId : XmlTagProblemAnalyzer
    {
        public override void Run(IXmlTag element, IHighlightingConsumer consumer)
        {
            if (element.GetProject().IsApplicableFor(this))
            {
                if (IsInvalid(element))
                {
                    SPC015210Highlighting errorHighlighting = new SPC015210Highlighting(element);
                    consumer.ConsumeHighlighting(element.Header.GetDocumentRange(), errorHighlighting);
                }
            }
        }

        public static bool IsInvalid(IXmlTag element)
        {
            bool result = false;

            if (element.Header.ContainerName == "ContentType" && element.AttributeExists("FeatureId"))
            {
                var attribute = element.GetAttribute("FeatureId");
                Guid fieldId = Guid.Empty;
                if (Guid.TryParse(attribute.UnquotedValue, out fieldId))
                    result = !attribute.UnquotedValue.Contains("{");
                else
                    result = true;
            }

            return result;
        }
    }

    [ConfigurableSeverityHighlighting(CheckId, XmlLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ShowToolTipInStatusBar = true)]
    public class SPC015210Highlighting : XmlErrorHighlighting
    {
        public const string CheckId = "SPC015210";
        public const string Message = "Define correct parent FeatureId in ContentType";

        public IXmlTag Element { get; private set; }

        public SPC015210Highlighting(IXmlTag element) :
            base(String.Format("{0}: {1}", CheckId, Message))
        {
            Element = element;
        }
    }
}
